<!-- 登录 -->
<template>
	<view class="observe-content">
		<image style="height: 200px; width: 100vw; position: fixed;" src="/static/images/observe/header-bg.png" />
		<image style="height: 150px; width: 150px; right: 20px; top: 50px; position: fixed;" src="/static/icons/icon_login_mark.png"></image>
		<image style="height: 60px; left: 20px; top: 80px; position: fixed;" mode="heightFix" src="/static/icons/icon_login_title.png"></image>
		<view
			style="position: absolute; z-index: 999; width: calc(100vw - 20px); padding: 40px 15px; background-color: white; border-radius: 20px 20px 0px 0px; margin: 150px 10px; ">
			<view class="cell">
				<text class="title">请输入账号</text>
				<view class="content">
					<input placeholder="请输入登录账号" v-model="username" />
				</view>
			</view>
			<view class="cell">
				<text class="title">密码</text>
				<view class="content">
					<input placeholder="请输入登录密码" password="true" v-model="password" />
				</view>
			</view>

			<view class="confirm" @click="submit()">登录</view>
		</view>
		<uni-load-more v-if="tableList.length > 0" :status="status" :contentText="contentText"></uni-load-more>

		<!-- 筛选时间 -->
		<u-datetime-picker ref="myElement" :show="selectDateShow" v-model="dateDaya" mode="year-month"
			confirmColor="#58C866" @cancel="selectDateShow = false" title="选择发表日期" v-on:confirm="confirmDate"
			v-on:change="changeDate"></u-datetime-picker>
		<!-- 添加按钮 -->
		<view class="add icon-add" @click="handleAddObserve" @touchstart="handleMouseDown"
			@touchmove.stop="handleMouseMove" @touchend="handleMouseUp" :style="{ top: top + 'px', left: left + 'px'}">
		</view>
		<!-- 弹框提示 -->
		<rf-toast :show="showWarn" @click="showWarn = false" :isSus="false" :title="errMsg"></rf-toast>

		<!-- 删除该观察记录确认弹窗 -->
		<rf-alert :show="confirmShow" @close="confirmShow=false" @confirm="confirm" title="提示"
			desc="确认删除该观察记录?"></rf-alert>

		<!-- 用户未注册 提示注册 -->
		<rf-alert :show="showRegister" @close="showRegister=false" @confirm="onClickRegister" title="提示" desc="您还未登录"
			confirmText="去登录"></rf-alert>

		<!-- 加载loading -->
		<rf-load :loading="loading" title="加载中..."></rf-load>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState,
	} from 'vuex'; //引入mapState
	import {
		login,
		detail,
		total,
		worker_list,
		add_worker
	} from '@/api/sgw.js'

	import {
		zip,
		Observable,
		Subject,
		pipe,
		from,
		observable,
		timer,
		interval,

	} from 'rxjs'

	import {
		retryWhen,
		takeWhile,
		concatMap,
		filter,
		switchMap,
		isEmpty,
	} from 'rxjs/operators'
	import toast from '../../uni_modules/uview-ui/libs/config/props/toast';



	// 创建两个主题
	const confirmSub = new Subject();
	const changeSub = new Subject();

	// 开始每3秒请求一次
	var source = null;

	export default {
		data() {
			return {
				navbarHeight: this.navBarHeight,
				screenWidth: this.screenWidth,
				screenHeight: this.screenHeight,
				status: "more",
				contentText: {
					contentdown: "查看更多",
					contentrefresh: "加载中...",
					contentnomore: "没有更多了",
				},
				ageList: [
					[{
						'name': '昨日',
						'value': "",
					}, {
						'name': '近7日',
						'value': "0.5",
					}, {
						'name': '近30日',
						'value': "1",
					}, {
						'name': '自定义',
						'value': "1.5",
					}]
				],
				aiList: [], // ai分析未完成的观察记录 ID

				confirmShow: false, // 删除确认窗口

				dateStr: '',
				week: '',


				nowMonth: '',
				nowDay: '',

				selectDateShow: false,
				assistantShow: false, // ai生成完成提示
				dateDaya: Number(new Date()),
				params: {
					pageSize: 10,
					pageNum: 1,
					year: '',
					month: ''
				},
				tableList: [],
				analyzeBtn: '展开',
				showAll: false,
				allList: [], // 弹出多个孩子的观察，孩子列表
				total: 0,

				dragging: false, // 是否正在拖拽
				mouseX: 0, // 鼠标在元素内的X坐标
				mouseY: 0, // 鼠标在元素内的Y坐标
				left: 0, // 元素左上角距离父容器左侧的距离
				top: 0, // 元素左上角距离父容器顶部的距离


				showWarn: false,
				errMsg: "",
				loading: false, // 加载中提示
				showRegister: false, // 用户未注册提示

				// 删除
				delId: "",
				delIndex: "",

				observe: "", // 分享传参

				currentTabidx: 0,

				shareParams: {
					name: "",
					homePhoto: "",
				},

				is_load: true,

				// username: "测试001", //用户名
				// password: "123456", //密码
				username: "", //用户名
				password: "", //密码
			};
		},

		// domStreams: ['confirmM$', 'change$'],
		// observableMethods: {
		// 	confirmM: 'confirmM$',
		// 	change: 'change$'
		// },
		subscriptions() {
			return {

			}
		},
		onTabItemTap(e) {
			// 点击tabbaritem键的触发，常用于刷新
			console.log("onTabItemTap" + JSON.stringify(e));
		},
		created() {
		},
		computed: {
			...mapState(['userInfo', 'hasLogin']),
		},
		onLoad(options) {

			this.left = this.screenWidth - 80;
			this.top = this.screenHeight - 180;

			const shareId = options.shareId;

			if (shareId != null && shareId != undefined) {
				uni.setStorageSync("inviter_uuid", shareId)
			} else {
				uni.setStorageSync("inviter_uuid", "")
			}

			// this.navbarHeight = this.screenWidth / 750 * 190;
			// this._login()

			let _that = this;



			// if (!_that.hasLogin) {
			// 	_that.tableList = []
			// 	return
			// }

		},
		mounted() {
			this.initTime();

			var _that = this;

		},
		onUnload() {
			uni.$off('shareParams')
		},
		onShow() {
			uni.$emit("onShow", null)
			let _that = this;
			_that.params.pageNum = 1;
			// _that.getObserveList()
		},
		onHide() {
			console.log("--------------onHide----------------");

		},

		methods: {
			...mapMutations(["login", "updateState"]),
			showTologin() {
				if (!this.hasLogin) {
					this.showRegister = true;
				}
			},
			// 确认去注册
			onClickRegister() {
				this.showRegister = false;
				uni.switchTab({
					url: "/pages/home/home"
				});

			},
		
			submit() {


				if (this.isEmptyStr(this.username)) {
					uni.showToast({
						title: "请输入登录账号",
						icon: "none",
					})
					return
				}

				if (this.isEmptyStr(this.password)) {
					uni.showToast({
						title: "请输入登录密码",
						icon: "none",
					})
					return
				}

				const data = {
					"username": this.username, //用户名
					"password": this.password, //密码
				};

				this.loading = true;
				let _that = this;
				login(data).then(res => {
					this.loading = false;
					if (res.code == 0) {
						_that.updateState(res.data)
						uni.showToast({
							title: "登录成功",
							icon: "none",
						})
						if(res.data.is_manger == "1"){
							uni.navigateTo({
								url: '/pages/observe/observe'
							})
						}else{
							uni.navigateTo({
								url: '/pages/observe/mainEmp'
							})
						}
						
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
						})
					}

				}).catch(err => {
					this.loading = false;
					uni.showToast({
						title: err.message,
						icon: "none",
					})
				})

			},
			isEmptyStr(str) {
				return (!str || str.trim().length === 0)
			},
			handle() {
				// 消除ai分析已完成的提示
				this.assistantShow = false
			},
			deepClone(obj) {
				if (obj === null || typeof obj !== 'object') {
					return obj;
				}

				let clone = Array.isArray(obj) ? [] : {};

				for (let key in obj) {
					if (obj.hasOwnProperty(key)) {
						clone[key] = this.deepClone(obj[key]);
					}
				}

				return clone;
			},

			getObserveList() {
				let _that = this
				this.status === 'loading'
				observeList(_that.params).then(res => {
					setTimeout(() => {
						this.loading = false;
					}, 1000)
					let dataList = res.data.rows ? res.data.rows : []
					console.log("getObserveList", res);
					_that.total = res.data.total
					if (_that.params.pageNum == 1) {
						_that.tableList = dataList
					} else {
						_that.tableList = _that.tableList.concat(dataList)
					}
					// if (dataList.length < _that.params.pageSize) {
					// 	_that.status = 'noMore';
					// } else {
					// 	_that.status = 'more';
					// }

					_that.aiList = []
					for (let i = 0; i < _that.tableList.length; i++) {
						var item = _that.tableList[i]
						if (item.status == 2) {
							// ai生成中，需要轮询 请求获取ai生成结果
							_that.aiList.push(item.id)
						}
					}
					// 去重
					_that.aiList = [...new Set(_that.aiList)];
					_that.getAiListDes()

				})
			},
			// 
			closeAll() {
				this.showAll = false
			},
			// 
			openShowAll(val) {
				this.allList = val
				this.showAll = true
				console.log(this.showAll)
			},
			lookImg: function(val) {
				const urls = val[0].map(item => {
					return item.url
				})
				const current = val[1]
				console.log(urls);
				console.log(current);

				uni.previewImage({
					urls,
					current
				})
			},
			// 初始化日期
			initTime() {
				const time = new Date();
				//获得系统年份;
				const year = time.getFullYear();
				//获得系统月份;
				const month = time.getMonth() + 1;
				//获得系统当月分天数;
				const day = time.getDate();
				//获得系统星期几;
				let dayCycle = time.getDay();
				//使用数组更改日期样式;
				const dayCycleArray = ["日", "一", "二", "三", "四", "五", "六"];
				for (let i = 0; i < 7; i++) {
					if (dayCycle == i) {
						//将dayCycleArray的数赋值到系统星期几里面中去;
						dayCycle = dayCycleArray[i];
					}
				}
				this.dateStr = year + '/' + month + '/' + day + ' ';
				this.week = '星期' + dayCycle;
				this.nowMonth = month;
				this.nowDay = day;
				this.nowYear = year;
			},
			selectDate() {
				// if (!this.hasLogin) {
				// 	this.showRegister = true;
				// 	return
				// }
				this.selectDateShow = true;

			},
			// 选定日期， 筛选观察
			confirmDate(e) {

				// console.log('confirmDate收到值:', uni.$u.timeFormat(e.value, 'yyyy mm'));
				// confirmSub.next(e)
				this.selectDateShow = false;
				// 搜索参数
				this.params.year = uni.$u.timeFormat(e.value, 'yyyy')
				this.params.month = uni.$u.timeFormat(e.value, 'mm')

				this.nowMonth = this.params.month;
				this.nowYear = this.params.year;
				this.nowDay = uni.$u.timeFormat(e.value, 'dd')

				this.params.pageNum = 1

				// 搜索观察
				this.getObserveList()
			},
			changeDate(e) {
				// console.log('changeDate收到值:', uni.$u.timeFormat(e.value, 'yyyy mm'));
				// changeSub.next(e)
			},

			// 删除观察
			handleDelete(id, idx) {
				let _that = this
				console.log(id, idx);
				this.delId = id;
				this.delIndex = idx;
				this.confirmShow = true

			},
			confirm() {
				console.log(this.delId, this.delIndex);
				let _that = this
				delObserve(this.delId).then(res => {
					console.log(res);
					console.log("res: " + JSON.stringify(res));
					if (res.code == 200) {
						_that.is_load = false
						_that.tableList.splice(_that.delIndex, 1)
						_that.confirmShow = false;
						_that.getObserveList()
					}
				}).catch(err => {
					_that.errMsg = "删除失败"
					_that.showWarn = true
				})
			},
			// 编辑当前观察记录
			handleEditObserve(item) {
				console.log("itemitem: " + JSON.stringify(item));
				uni.navigateTo({
					url: '/pages-sub/observeAdd/addObserve?type=update&item=' + encodeURIComponent(JSON.stringify(
						item))
				})
			},
			// 观察分析关闭事件
			handleAnalyzeClose(index) {
				let _that = this

				clearTimeout(this.timer)
				this.timer = null
				this.timer = setTimeout(() => {
					_that.tableList[index].expanded = false;
					_that.$forceUpdate();
				}, 300);
			},
			// 观赏分析展开事件
			handleAnalyzeOpen(index) {
				this.tableList[index].expanded = true;
				this.$forceUpdate();
			},
			// 新增观察记录
			handleAddObserve() {
				if (!this.hasLogin) {
					this.showRegister = true;
					return
				}
				if (this.currentTabidx == 0) {
					uni.navigateTo({
						url: '/pages-sub/observeAdd/addObserve?type=create'
					});
				} else {
					uni.navigateTo({
						url: '/pages-sub/addEval/addEval?type=create'
					});
				}
			},
			handleMouseDown(event) {
				this.dragging = true;
				this.mouseX = event.changedTouches[0].clientX;
				this.mouseY = event.changedTouches[0].clientY;
			},
			handleMouseMove(event) {
				if (this.dragging) {
					console.log("event", event);
					console.log("screenWidth", this.screenWidth);
					console.log("screenHeight", this.screenHeight);
					const deltaX = event.changedTouches[0].clientX - this.mouseX;
					const deltaY = event.changedTouches[0].clientY - this.mouseY;

					var left = this.left + deltaX;
					var top = this.top + deltaY;
					if (left <= 0) {
						this.left = 0
					} else if (left >= (this.screenWidth - 60)) {
						this.left = (this.screenWidth - 60)
					} else {
						this.left = left;
					}
					if (top <= 0) {
						this.top = 0
					} else if (top >= (this.screenHeight - 100)) {
						this.top = (this.screenHeight - 100)
					} else {
						this.top = top;
					}
					this.mouseX = event.changedTouches[0].clientX;
					this.mouseY = event.changedTouches[0].clientY;
				}
			},
			handleMouseUp(event) {
				console.log(event);
				this.dragging = false;
			},
		},
		onReachBottom() {
			uni.$emit('onReachBottom', null);
			if (this.is_load == false) {
				this.is_load = true
				return
			}

			if (this.tableList.length >= this.total) {
				this.status = 'noMore';
			} else {
				this.status = 'more';
				this.params.pageNum++
				this.getObserveList()
			}

		},
		onReady() {
			//  设置 top 时间，显示最新一条信息的时间
			setTimeout(() => {
				if (this.tableList.length > 0) {
					const query = uni.createSelectorQuery().in(this);
					query.selectAll('.table-list').boundingClientRect(data => {
						let temp = data[0].dataset.time.split(' ')[0].split('-')
						this.nowDay = temp[2]
						this.nowMonth = temp[1]
						this.nowYear = temp[0]
					}).exec();
				}
			}, 1000)

		},
		onPageScroll: function(e) {
			uni.$emit('onPageScroll', e);
			if (this.tableList.length > 0) {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.table-list').boundingClientRect(data => {
					for (let index = 0; index < data.length; index++) {
						if (data[index].top > 190 && data[index].top < 300) {
							let temp = data[index].dataset.time.split(' ')[0].split('-')
							this.nowDay = temp[2]
							this.nowMonth = temp[1]
							this.nowYear = temp[0]
							break
						};
					}
				}).exec();

			}
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}

	.confirm {
		height: 40px;
		width: 100%;
		background-color: #FF8D1A;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 20px;
		margin-top: 30px;
		color: white;

	}

	.cell {
		width: 100%;
		height: 80px;

		.title {
			color: #999999;
		}

		.content {
			width: 100%;
			margin-top: 10px;
			height: 30px;

			input {
				height: 40px;
				border-radius: 20px;
				padding: 0px 15px 0px 15px;

				background-color: #F5F5F5;
			}
		}
	}

	.container {
		width: 100%;
		height: 100%;
	}

	.select-date {
		// margin-top: 32rpx;
		position: relative;
		padding-right: 45rpx;
		// flex: 1;

		&:before {
			content: '';
			width: 0;
			height: 0;
			position: absolute;
			right: 0;
			top: 3px;
			border-top: 10px solid #3A3D4B;
			border-left: 8px solid transparent;
			border-right: 8px solid transparent;
		}
	}

	.bgNum1 {
		background-color: transparent;
		background-image: url('../../static/icons/bg_card_num1.png');
		background-size: cover;
		/* 覆盖整个容器，可能裁剪图片 */
		background-size: contain;
		/* 完整显示图片，可能留白 */
		background-size: 100% 100%;
		/* 拉伸填充容器 */
		// background-size: 50% auto;
		/* 指定宽度，高度自动 */
	}

	.title {
		font-weight: bold;

		.line {
			background: url('../../static/images/common/bg_line.png');
			width: 60px;
			height: 20px;
			background-repeat: no-repeat;
			background-size: 100%;
			margin-top: -10px;
		}
	}

	.observe-content {

		.header {
			display: flex;
			flex-direction: column;
			position: relative;
			z-index: 1;
			top: 0;
			background-color: #9CED9C;


			.header-bg {
				width: 100%;
				height: 100%;
			}

			.date {}

			.hierarchy-up {
				top: 17px;
				// position: absolute;
				// width: 100%;
				// z-index: 9;
			}

			.dateContent {
				width: 100%;
				position: absolute;
				z-index: inherit;
				top: 50%;
				transform: translateY(-50%);
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 80rpx 0 98rpx;
			}

			.circle-button {
				position: relative;
				width: 40rpx;
				height: 40rpx;
				border-radius: 100%;
				background-color: white;
				margin-left: 10rpx;

			}

			.arrow-right {
				content: "";
				height: 18rpx;
				width: 18rpx;
				border-color: #58C866;
				border-style: solid;
				position: absolute;
				top: 12rpx;
				left: 8rpx;
				border-width: 6rpx 6rpx 0 0;
				transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
			}

			.new-btn {
				width: 196rpx;
				height: 72rpx;
				background: linear-gradient(180deg, #79EE88 0%, #58C866 100%);
				box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(25, 111, 56, 0.24), inset 0rpx 2rpx 6rpx 0rpx rgba(255, 255, 255, 0.5), inset 0rpx -2rpx 6rpx 0rpx rgba(255, 255, 255, 0.23);
				border-radius: 36rpx;

				display: flex;
				align-items: center;
				justify-content: center;

				.new-text {
					color: #fff;
					text-shadow: 0px 4px 8px rgba(25, 111, 56, 0.24);
				}

			}
		}

		.observe-body {
			padding: 20px 10px;
			width: 100vw;
			min-height: 70vh;

			background-color: #FFF5F5F5;



			.card {
				position: relative;
				margin-top: 20px;
				width: 100vb;
				border-radius: 10px;
				/* 确保子元素也遵循圆角 */
				overflow: hidden;

				.bg {
					padding: 20px;
					background-color: white;
				}

				.avatar {
					display: flex;
					align-items: center;

					image {
						height: 40px;
						width: 40px;
						background-color: white;
						border-radius: 50%;
						/* 创建完美圆形 */
					}
				}

				.title {
					font-weight: bold;

					.line {
						background: url('../../static/images/common/bg_line.png');
						width: 60px;
						height: 20px;
						background-repeat: no-repeat;
						background-size: 100%;
						margin-top: -10px;
					}
				}

				.content {

					align-content: center;
					height: 50px;

					.num {
						font-size: 30px;
					}

					.unit {
						font-size: 16px;
					}
				}

				.icon {
					height: 100px;
					width: 100px;
					position: absolute;
					right: 0px;
					bottom: 0px;
				}
			}

			.sticky_container {
				background-color: white;
				padding: 10rpx 0 0 0;
				border-radius: 36rpx 36rpx 0 0;

				.tab {
					background-color: #fff;
					display: flex;
					align-items: center;
					margin: 10rpx 30rpx 0 30rpx;
					height: 80rpx;

					.highlight_tab {
						width: 128rpx;
						height: 60rpx;

						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: space-between;

						.text {
							font-size: 32rpx;
							font-family: PingFangSC, PingFang SC;
							font-weight: 600;
							color: #3A3D4B;
							line-height: 44rpx;
						}

						.bottom_line {
							background-color: #58C866;
							width: 60rpx;
							height: 8rpx;
							border-radius: 4rpx;
						}

					}

					.normal_tab {
						width: 128rpx;
						height: 60rpx;

						display: flex;
						flex-direction: column;
						justify-content: center;
						justify-content: space-between;

						.text {
							font-size: 28rpx;
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							color: #3A3D4B;
							line-height: 40rpx;
						}

					}

				}

				.date {
					background-color: #fff;
					height: 80rpx;
					padding: 0 32rpx;
					display: flex;
					justify-content: space-between;
					align-items: flex-end;

					.now-date {
						// margin-top: 32rpx;
						// flex: 1;
					}

					.select-date {
						// margin-top: 32rpx;
						position: relative;
						padding-right: 45rpx;
						// flex: 1;

						&:before {
							content: '';
							width: 0;
							height: 0;
							position: absolute;
							right: 0;
							top: 15rpx;
							border-top: 15rpx solid #3A3D4B;
							border-left: 15rpx solid transparent;
							border-right: 15rpx solid transparent;
						}
					}
				}
			}
		}
	}
</style>